<template>
    <div class="content_box">
        <h2>{{ title }}</h2>
        <ul>
            <li class="list_item"
                v-for="(item,index) in list"
                :key="index"
                @dblclick="onChangeItem(index)">
                <span v-show="index !== showInput">{{ item }}</span>
                <input v-if="index === showInput"
                       v-model="list[index]"
                       ref="changeInput"
                       @blur="onInputBlur"
                       @keydown.enter="onInputBlur"
                       type="text">
                <span @click="onDeleteItem(index)" class="delete_btn">删除</span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    name: "ContentBox",
    props: ["title", "list"],
    data(){
        return {
            showInput:-1
        }
    },

    activated() {
        this.Bus.$on("sendText",(itemText)=>{
            console.log("在created生命周期中进行事件监听",this.list,itemText);
            this.list.push(itemText)
        })
    },
    deactivated() {
        console.log("destroyed---->");
        this.Bus.$off("sendText")
    },
    methods:{
        //双击进行修改操作
        onChangeItem(index){
            this.showInput = index;
            this.$nextTick(_ => {
                this.$refs.changeInput[0].focus();
            });
        },
        //对数组中的某一项进行删除
        onDeleteItem(index){
            this.list.splice(index, 1);
        },
        //光标离开
        onInputBlur(){
            this.showInput = -1;
        }
    }
}
</script>

<style scoped lang="scss" type="text/scss">
.content_box {
    height: 250px;
    border: 2px solid rgb(195, 218, 195);

    h2 {
        margin: 20px auto;
        text-align: center;
    }
    ul{
        height: 178px;
        overflow: auto;
    }
    .list_item {
        list-style: none;
        position: relative;
        padding: 0 20px;
        height: 30px;
        line-height: 30px;
        .delete_btn {
            display: none;
            position: absolute;
            right: 20px;
            cursor: pointer;
        }
        &:hover {
            .delete_btn{
                display: inline-block;
            }
            color: #fff;
            background-color: rgb(189, 255, 255);
        }
    }
}
</style>